module(..., package.seeall)

function new(obj)
	local ui = require("ui")

	local menuGroup = display.newGroup()
	local tapSound = audio.loadSound( "tapsound.wav" )
	
	local menuGroupLogin 		= nil
	local menuGroupRegister 	= nil
	local email 				= ""
	local pass 				= ""
	---------------------------------------------
	--
	---------------------------------------------
	function loadLogin()
		local path = system.pathForFile( "logins.txt", system.DocumentsDirectory )
		local fh, reason = io.open(path, "r")
		local info = "" --format true|email|pass
		if fh then
		   -- read all contents of file into a string
		   info = fh:read( "*a" )
		   io.close( fh )
		else
			--info = "true|tatuanvn@gmail.com|123"
		end
		if info ~= "" then
			--email = info
			local logs = slipWords(info, '|')
			email = logs[2]
			pass = logs[3]
			print(pass)
		end
	end
	---------------------------------------------
	--save info login
	---------------------------------------------
	function saveLogin(email, pass)
		local path = system.pathForFile( "logins.txt", system.DocumentsDirectory )
		-- io.open opens a file at path. returns nil if no file found
		local fh, reason = io.open(path, "w")
		--fh:write(email)
		fh:write("true|" .. email .. "|" .. pass)
		--[[if autoSavePassword then	
			fh:write("true|" .. emaillogin .. "|" .. passwordlogin)
		else
			fh:write("false|" .. emaillogin .. "|" .. passwordlogin)
		end--]]
		io.close( fh )
	end
	---------------------------------------------
	--
	---------------------------------------------
	function slipWords(str, key)
		local k = 1
		local index = 1
		local data = {}
		while index > 0 do
			local i, j = string.find(str, key, k)
			if i == nil then
				data[index] = str:sub(k)
				--print(data[index])
				index = -1
			else
				--print(i .. " - " .. j)
				local si = str:sub(k, i - 1)
				data[index] = si
				--print(data[index])
				k = j + 1
			end
			index = index + 1
		end
		return data
	end
	-----------------------------------------------------
	--Form dang ky
	-----------------------------------------------------
	function showFormRegister(grp)
		if menuGroupRegister == nil then
			menuGroupRegister = display.newGroup()
			grp:insert(menuGroupRegister)
			grp:addEventListener( "tap", function( event )
				native.setKeyboardFocus( nil )
			end)
			
			bgFormRegister = display.newImage("images/bgFormRegister.png")
			bgFormRegister.x = display.contentWidth/2
			bgFormRegister.y = display.contentHeight/2
			menuGroupRegister:insert(bgFormRegister)
			--Textbox email
			if system.getInfo( "environment" ) == "simulator" then
				txtEmail = display.newRect(bgFormRegister.x - bgFormRegister.width/2 + 40, bgFormRegister.y - bgFormRegister.height/2 + 82, 228, 28)
				txtEmail:setFillColor(200, 200, 200)
				menuGroupRegister:insert(txtEmail)
			else
				txtEmail = native.newTextField(bgFormRegister.x - bgFormRegister.width/2 + 40, bgFormRegister.y - bgFormRegister.height/2 + 82, 228, 28, function( event )
						if ( "began" == event.phase ) then
						elseif ( "ended" == event.phase ) then
						elseif ( "submitted" == event.phase ) then
							native.setKeyboardFocus( nil )
						end
					end)
				txtEmail.font = native.newFont( native.systemFontBold, inputFontSize )
				txtEmail.inputType = "email"
				menuGroupRegister:insert(txtEmail)
			end
					
			--Textbox mat khau
			if system.getInfo( "environment" ) == "simulator" then
				txtPass = display.newRect(bgFormRegister.x - bgFormRegister.width/2 + 40, bgFormRegister.y - bgFormRegister.height/2 + 136, 228, 28)
				txtPass:setFillColor(200, 200, 200)
				menuGroupRegister:insert(txtPass)
			else
				txtPass = native.newTextField(bgFormRegister.x - bgFormRegister.width/2 + 40, bgFormRegister.y - bgFormRegister.height/2 + 136, 228, 28, function( event )
						if ( "began" == event.phase ) then
						
						elseif ( "ended" == event.phase ) then
						
						elseif ( "submitted" == event.phase ) then
							native.setKeyboardFocus( nil )
						end
					end)
				txtPass.font = native.newFont( native.systemFontBold, 14)
				txtPass.isSecure = true
				menuGroupRegister:insert(txtPass)
			end
			
			if system.getInfo( "environment" ) == "simulator" then
				txtRePass = display.newRect(bgFormRegister.x - bgFormRegister.width/2 + 40, bgFormRegister.y - bgFormRegister.height/2 + 190, 228, 28)
				txtRePass:setFillColor(200, 200, 200)
				menuGroupRegister:insert(txtRePass)
			else
				txtRePass = native.newTextField(bgFormRegister.x - bgFormRegister.width/2 + 40, bgFormRegister.y - bgFormRegister.height/2 + 190, 228, 28, fieldHandler )
				txtRePass.font = native.newFont( native.systemFontBold, 14)
				txtRePass.isSecure = true
				menuGroupRegister:insert(txtRePass)
			end
			
			btnRegister = ui.newMyButton{
				default = "images/btnRegister.png",
				over = "images/btnRegisterOver.png",
				onRelease = function(event)
					theTimer = timer.performWithDelay(50, function(event)
						--Thuc hien dang ky
						local email = "duthi2013@gmail.com"
						local pass  = "123456"
						if system.getInfo( "environment" ) ~= "simulator" and (txtEmail.text == nil or txtEmail.text == "") then
							native.showAlert( "", "Đại chỉ email không hợp lệ!", { "OK"}, onComplete)
							return
						elseif system.getInfo( "environment" ) ~= "simulator" and (txtPass.text == nil or txtPass.text == "") then
							native.showAlert( "", "Mật khẩu không hợp lệ!", { "OK"}, onComplete)
							return
						elseif system.getInfo( "environment" ) ~= "simulator" and (txtEmail.text ~= txtPass.text == "") then
							native.showAlert( "", "Mật khẩu bạn nhập lần 2 không đúng!", { "OK"}, onComplete)
							return
						elseif system.getInfo( "environment" ) ~= "simulator" then
							email = txtEmail.text
							pass  = txtPass.text
						end
						
						local xmlTree = xml:doQuery("http://" .. serverConnect .. "/server.ashx?action=OLPASIGNUP&fullname=&email=" .. email .. "&pass=" .. pass)
						
						if xmlTree ~= nil then
							local REGISTER = xml:xmlNodes(xmlTree, "REGISTER")	
							if REGISTER ~= nil then
								for i, xmlNode in pairs(REGISTER) do
									if(xmlNode.Name == "RS") then
										result = xml:xmlValue(xmlNode, "result")
										if result == "OK" then
											--Xoa form dang ky
											cleanGroups(menuGroupRegister, 0)
											menuGroupRegister = nil
											showFormLogin(grp, email)
										end
										--Loi email (da dang ky hoac email khong hop le)
										if result == "EREMAIL" then
											native.showAlert("", "Địa chỉ email đã được đăng ký!", { "OK"}, onComplete)
										end
										if result == "ER" then
											native.showAlert("", "Địa chỉ email đã được đăng ký!", { "OK"}, onComplete)
										end
									end
								end
							end
						end
					end, 1)
				end
			}
			btnRegister.x = display.contentWidth/2 - btnRegister.width/2 - 32
			btnRegister.y = bgFormRegister.y + bgFormRegister.height/2 - 30
			menuGroupRegister:insert(btnRegister)
			
			btnCloseLogin = ui.newMyButton{
				default = "images/btnCloseLogin.png",
				over = "images/btnCloseLogin.png",
				onRelease = function(event)
					theTimer = timer.performWithDelay(50, function(event)
						--Xoa form login
						cleanGroups(menuGroupRegister, 0)
						menuGroupRegister = nil
					end, 1)
				end
			}
			btnCloseLogin.x = bgFormRegister.x + bgFormRegister.width/2 - btnCloseLogin.width/5
			btnCloseLogin.y = bgFormRegister.y - bgFormRegister.height/2
			menuGroupRegister:insert(btnCloseLogin)
		end
	end
	-----------------------------------------------------
	--Form login
	-----------------------------------------------------
	function showFormLogin(grp, email)
		if menuGroupLogin == nil then
			menuGroupLogin = display.newGroup()
			grp:insert(menuGroupLogin)
			grp:addEventListener( "tap", function( event )
				native.setKeyboardFocus( nil )
			end)
			
			bgFormLogin = display.newImage("images/bgFormLogin.png")
			bgFormLogin.x = display.contentWidth/2
			bgFormLogin.y = display.contentHeight/2
			menuGroupLogin:insert(bgFormLogin)
			--Textbox email
			if system.getInfo( "environment" ) == "simulator" then
				txtEmail = display.newRect(bgFormLogin.x - bgFormLogin.width/2 + 54, bgFormLogin.y - bgFormLogin.height/2 + 100, 200, 28)
				txtEmail:setFillColor(200, 200, 200)
				menuGroupLogin:insert(txtEmail)
			else
				txtEmail = native.newTextField(bgFormLogin.x - bgFormLogin.width/2 + 54, bgFormLogin.y - bgFormLogin.height/2 + 100, 200, 28, function( event )
						if ( "began" == event.phase ) then
						
						elseif ( "ended" == event.phase ) then
						
						elseif ( "submitted" == event.phase ) then
							native.setKeyboardFocus( nil )
						end
					end)
				txtEmail.font = native.newFont( native.systemFontBold, inputFontSize )
				txtEmail.inputType = "email"
				if email then
					txtEmail.text = email
				end
				menuGroupLogin:insert(txtEmail)
			end
			--Textbox mat khau
			if system.getInfo( "environment" ) == "simulator" then
				txtPass = display.newRect(bgFormLogin.x - bgFormLogin.width/2 + 54, bgFormLogin.y - bgFormLogin.height/2 + 160, 200, 28)
				txtPass:setFillColor(200, 200, 200)
				menuGroupLogin:insert(txtPass)
			else
				txtPass = native.newTextField(bgFormLogin.x - bgFormLogin.width/2 + 54, bgFormLogin.y - bgFormLogin.height/2 + 160, 200, 28, function( event )
						if ( "began" == event.phase ) then
						elseif ( "ended" == event.phase ) then
						elseif ( "submitted" == event.phase ) then
							native.setKeyboardFocus( nil )
						end
					end)
				txtPass.font = native.newFont( native.systemFontBold, inputFontSize )
				txtPass.isSecure = true
				menuGroupLogin:insert(txtPass)
				if pass then
					txtPass.text = pass
				end
			end
			
			btnLogin = ui.newMyButton{
				default = "images/btnLogin.png",
				over = "images/btnLoginOver.png",
				onRelease = function(event)
					--Thuc hien login he thong
					if system.getInfo( "environment" ) ~= "simulator" and (txtEmail.text == nil or txtEmail.text == "") then
						native.showAlert( "", "Địa chỉ email không hợp lệ!", { "OK"}, onComplete)
					else
						local email = "tatuanvn@gmail.com"
						local pass  = "123456"
						
						if system.getInfo( "environment" ) ~= "simulator" then
							email = txtEmail.text
							pass  = txtPass.text
						end
						local xmlTree = xml:doQuery("http://" .. serverConnect .. "/server.ashx?action=OLPASIGNIN&email=" .. email .. "&pass=" .. pass)
						
						if xmlTree ~= nil then
							local LOGIN = xml:xmlNodes(xmlTree, "LOGIN")	
							if LOGIN ~= nil then
								for i, xmlNode in pairs(LOGIN) do
									if(xmlNode.Name == "RS") then
										result = xml:xmlValue(xmlNode, "result")
										if result == "OK" then
											saveLogin(email, pass)
											fullname = xml:xmlValue(xmlNode, "fullname")
											level = xml:xmlValue(xmlNode, "level")
											score = xml:xmlValue(xmlNode, "score")
											retest= xml:xmlValue(xmlNode, "retest")
											order= xml:xmlValue(xmlNode, "order")
											--
											cleanGroups(menuGroupLogin, 0)
											menuGroupLogin = nil
											
											obj = {}
											obj.fullname = fullname
											obj.email = email
											obj.pass = pass
											obj.level = level
											obj.score = tonumber(score)
											obj.retest = tonumber(retest)
											obj.order = tonumber(order)
											director:changeScene("lenduong", obj)
										end
										if result == "ERPASS" then
											native.showAlert("", "Sai m?t kh?u dang nh?p!", {"OK"}, onComplete)	
										end
										if result == "EREMAIL" then
											native.showAlert("", "Email dang nh?p chua t?n t?i!", {"OK"}, onComplete)
										end
									end
								end
							end
						end
					end
				end
			}
			btnLogin.x = display.contentWidth/2 + btnLogin.width/2 + 32
			btnLogin.y = bgFormLogin.y + bgFormLogin.height/2 - 30
			menuGroupLogin:insert(btnLogin)
			
			btnRegister = ui.newMyButton{
				default = "images/lblRegister.png",
				over = "images/lblRegister.png",
				onRelease = function(event)
					theTimer = timer.performWithDelay(50, function(event)
						--Xoa form login
						cleanGroups(menuGroupLogin, 0)
						menuGroupLogin = nil
						showFormRegister(grp, name)
					end, 1)
				end
			}
			btnRegister.x = display.contentWidth/2 - btnRegister.width/2 + 10
			btnRegister.y = bgFormLogin.y + bgFormLogin.height/2 - 30
			menuGroupLogin:insert(btnRegister)
			
			btnCloseLogin = ui.newMyButton{
				default = "images/btnCloseLogin.png",
				over = "images/btnCloseLogin.png",
				onRelease = function(event)
					theTimer = timer.performWithDelay(50, function(event)
						--Xoa form login
						cleanGroups(menuGroupLogin, 0)
						menuGroupLogin = nil
					end, 1)
				end
			}
			btnCloseLogin.x = display.contentWidth/2 + bgFormLogin.width/2 - btnCloseLogin.width/2
			btnCloseLogin.y = bgFormLogin.y - bgFormLogin.height/2
			menuGroupLogin:insert(btnCloseLogin)
		end
	end
	---------------------------------------------
	--init screen
	---------------------------------------------
	function drawScreen()
		
		bg = display.newImageRect("images/bgmainmenu.png", display.contentWidth, display.contentHeight)
		bg.x = display.contentWidth/2
		bg.y = display.contentHeight/2
		menuGroup:insert(bg)
		
		btnTheLe = ui.newMyButton{
			default = "images/btnTheLe.png",
			over = "images/btnTheLeOver.png",
			onRelease = function(event)
				director:changeScene("thele", sound, "")
			end
		}
		btnTheLe.x = 56
		btnTheLe.y = 282
		menuGroup:insert(btnTheLe)	
		
		btnDangKy = ui.newMyButton{
			default = "images/btnDangKy.png",
			over = "images/btnDangKyOver.png",
			onRelease = function(event)
				showFormRegister(menuGroup)
			end
		}
		btnDangKy.x = 325
		btnDangKy.y = 282
		menuGroup:insert(btnDangKy)	
		
		btnThamGia = ui.newMyButton{
			default = "images/btnThamGia.png",
			over = "images/btnThamGiaOver.png",
			onRelease = function(event)
				--director:changeScene("lenduong", sound, "style02")
				--yeu cau login truoc khi len duong du thi
				showFormLogin(menuGroup, email)
			end
		}
		btnThamGia.x = 421
		btnThamGia.y = 282
		menuGroup:insert(btnThamGia)	
		
		if obj and obj.showlogin == true then
			showFormLogin(menuGroup, email)
		end
	end
	loadLogin()
	
	--Init gameplay screen
	drawScreen()
	
	---------------------------------------------
	--xoa du lieu
	---------------------------------------------
	function cleanGroups (curGroup, level)
		if curGroup.numChildren then
			while curGroup.numChildren > 0 do
				cleanGroups (curGroup[curGroup.numChildren], level+1)
			end
			if level > 0 then
				curGroup:removeSelf()
				curGroup = nil
			end
		else
			curGroup:removeSelf()
			curGroup = nil
			return
		end
	end
	
	unloadMe = function()
	end
	return menuGroup
end